package com.lagou.consumer;

import com.lagou.common.pojo.FlashSale;
import com.lagou.common.pojo.Order;
import com.lagou.common.service.FlashSaleService;
import com.lagou.common.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Component
@RocketMQMessageListener(topic = "order-mq",consumerGroup =
        "springboot-mq-consumer-1")
public class OrderConsumer implements RocketMQListener<Order> {

    private int overdueSeconds = 10;


    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderService orderService;

    private void sendOverdueDelayMessage(Order order) {
        System.out.print("发送延迟消息： ");
        System.out.println(order);

        // delayLevel为3，延迟支付时间为10秒钟
        rocketMQTemplate.syncSend("payment-delay-mq", MessageBuilder.withPayload(order).build(), 2000, 3);
    }

    @Override
    public void onMessage(Order order) {
//        log.info(message);
        System.out.println(order);

        // 保存订单并减库存
        orderService.createOrder(order);

        // 发送延时消息来进行来判断延时支付是否过期
        sendOverdueDelayMessage(order);
    }


}